import React from 'react';
import { asyncComponent } from 'react-async-component';
import { ListAdvanced, RouteLayout, SearchAdvanced, TabPage } from 'weaver-mobile-page';
import { inject, observer } from 'mobx-react';
import { TextareaItem, Button, RichEditor, Icon, Picker, Tools, Popover, Bubble, Flex } from 'weaver-mobile';
import { toJS } from 'mobx';
import { Link, withRouter, Route } from 'react-router-dom';
import { forwardViewForm, transQueryParams, forwardViewPage } from '../../../util/common';
import allStore from './../../../stores'
import { getSecondAuthConfig4List } from "../../../../workflowpublic/apis/secondAuth";
import SecondAuthDialog from "../../secondauth/index";
import FollowList from "../../follow/index";
import TagManage from "../../follow/tagManage";
import TagEdit from "../../follow/tagEdit";
import * as authTypes from "../../../constants/secondAuthType";
import { openQYSAuth } from "../../../util/secondAuthUtil";
import { QYSUKeyUtil } from './../../../util/QYSUkeyUtil'
import * as EmSDK from './../../../util/emSDK'
const Item = TabPage.Item;

const ButtonGroup = RouteLayout.ButtonGroup;
const getLabel = Tools.getLabel;
const btnNames = { 'batchSubmit': getLabel(17598, '批量提交'), 'batchSupervise': getLabel(84561, '批量督办'), 'batchAttention': getLabel(503955, '批量关注') };

const coms = {
    QYSAuth: asyncComponent({
        resolve: () => import("../../secondauth/index")
    })
}

@inject('workflowCenterStore', 'secondAuthStore')
@withRouter
@observer
class WorkflowCenter extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            date:new Date(),
            originalHeight:document.body.clientHeight || document.documentElement.clientHeight
        }
    }

    componentWillMount() {
        const { location } = this.props;
        const queryParams = transQueryParams(location);
        const { nowStore, nowScope, setSignRemark, setStore, getData, setState, retainCondition, menuid, getRetainDatas,nowViewScope } = this.props.workflowCenterStore;
        const ss = Tools.ss;
        if (!queryParams.hasOwnProperty("moduleid")) {
            queryParams.moduleid = 10;//以前发布到em和企业微信的应该都是moduleid等于10的默认流程中心应用，组件发布时，没有设置功能的应用不会传参到企微和钉钉，导致以前集成过去的的流程中心应用全都不带moduleid
        }
        setState({ menuid: queryParams.moduleid });

        if (window.sessionStorage && sessionStorage.getItem("__wf__list__retain__retainCondition")) {

        } else if (retainCondition === 1 || queryParams.hasOwnProperty("moduleid")) {//单应用打开/保留条件


        } else {//流程中心打开
            //nowStore.clear();
            //getData();

        }
        setSignRemark();
        EmSDK.controlEmTopNav({title:nowViewScope.title});
    }

    //👇 retainCondition=1
    componentDidMount() {
        //const { queryParams, menuid, nowStore, nowScope, setSignRemark, setStore, getData, nowStore: { searchAdvancedStore }, nowViewScope, retainCondition, getRetainDatas } = this.props.workflowCenterStore;
        // if (menuid === -1) {//&& window.sessionStorage && sessionStorage.getItem("__wf__list__retain__retainCondition")
        //     searchAdvancedStore.getData({
        //         url: nowViewScope.name === "all" || nowViewScope.name === "attentionAll" ? nowViewScope.conditionUrl : nowViewScope.treeUrl,
        //         method: 'POST',
        //         params: queryParams
        //     }).then((form) => {
        //         if (retainCondition === 1) {//保留条件
        //             setStore();
        //         }
        //     });
        // }

        window.addEventListener('resize', this.resize);
    }

    resize = () => {
        const { originalHeight } = this.state;
        const currentHeight = document.body.clientHeight || document.documentElement.clientHeight;
        if(currentHeight <= originalHeight){//监听页面高度，强制渲染一次解决安卓软键盘高度问题
           this.setState({date:new Date()}); 
        }
    }

    componentWillUnmount(){
        window.removeEventListener('resize',this.resize);
    }

    componentWillUpdate(nextProps) {
        const location = this.props.location || {};
        const nextLocation = nextProps.location || {};
        const { nowViewScope } = this.props.workflowCenterStore;
        if (location.pathname !== nextLocation.pathname) {
            EmSDK.controlEmTopNav({title:nowViewScope.title});
        }
    }

    onLeftTreeChange = (domid, name, valueArray) => {
        const { queryParams, nowStore, nowViewScope, nowScope, setSignRemark, setStore, getData, onSearch, setState } = this.props.workflowCenterStore;
        const fileds = {};
        const workflowtype = nowViewScope.name === "all" ? "typeid" : "workflowtype";
        if (/^wf_-?\d+/.test(domid)) {
            fileds.workflowid = { value: [{ id: domid.replace(/^wf_/, ''), name }] };
            fileds[workflowtype] = { value: [] };

            if (nowViewScope.name === "attentionAll") {
                fileds.workflowId = domid.replace(/^wf_/, '');
                fileds.workflowid = fileds.workflowId;
                fileds.workflowidspan = name;
                fileds.workflowtype = '';
                fileds.workflowtypespan = '';
            }
        }
        if (/^type_-?\d+/.test(domid)) {
            fileds[workflowtype] = { value: [{ id: domid.replace(/^type_/, ''), name }] };
            fileds.workflowid = { value: [] };

            if (nowViewScope.name === "attentionAll") {
                fileds.workflowType = domid.replace(/^type_/, '');
                fileds.workflowtype = fileds.workflowType;
                fileds.workflowtypespan = name;
                fileds.workflowid = '';
                fileds.workflowidspan = '';
            }
        }
        if (domid === '') {
            fileds[workflowtype] = { value: [] };
            fileds.workflowid = { value: [] };

            if (nowViewScope.name === "attentionAll") {
                fileds.workflowType = "";
                fileds.workflowId = "";
                fileds.workflowtype = '';
                fileds.workflowid = '';
            }
        }
        if (nowViewScope.name === "attentionAll") {
            setState({ queryParams: fileds });
        }

        // 同步树选中项到高级搜索的 from 中
        if (!nowStore.searchAdvancedStore) {
            nowStore.setState({
                searchAdvancedStore: new SearchAdvanced.Store({
                    route: nowStore.route,
                    id: nowScope,
                })
            });
            nowStore.searchAdvancedStore.getData({
                url: '/api/workflow/reqlist/doingBaseInfo',
                method: 'POST',
                params: queryParams
            }).then((form) => {
                if (nowStore.searchParams.requestname) {
                    fileds.requestname = { value: nowStore.searchParams.requestname };
                }
                form.updateFields(fileds);
                onSearch();
            });
        } else {
            nowStore.searchAdvancedStore.form.updateFields(fileds);
            onSearch();
        }
        setState({ leftTreeValueArray: valueArray });
    };

    getButtonText = () => {
        const { popSelectKey } = this.props.workflowCenterStore;
        if (popSelectKey == 2) {
            return "批量关注"
        } else {
            return '批量提交'
        }
    }
    getSwipeActionProps = () => ({
        right: [
            {
                text: getLabel('521940', '标记为已读'),
                onPress: (data) => {
                    const { doReadIt } = this.props.workflowCenterStore;
                    doReadIt({ opertype: "single", requestid: data.requestid, fromQuickSearch: "false",f_weaver_belongto_userid:data.userid,f_weaver_belongto_usertype:data.usertype });
                },
                className: `swipeFollow`,
                style: { width: "100px", background: "#bfbfbf" },
            }, {
                text: getLabel('25436', '关注'),
                onPress: (data) => {
                    const { layout, nowStore } = this.props.workflowCenterStore;
                    this.props.history.push({
                        pathname: nowStore.route + '/follow',
                        state: {
                            requestids: data.requestid,
                            mode: 'single',
                            flag: 'workflow',
                            route: nowStore.route,
                        }
                    })
                },
                className: `swipeFollow`,
                style: { width: "100px" },
            },
        ],
    })
    render() {
        const {
            showCheck,
            setState,
            nowStore,
            requestBatchSubmit,
            nowScope,
            mask,
            saveStore,
            changeCheck,
            buttonGroupData,
            phrasesDatas,
            needRemark,
            multisubmitnotinputsign,
            onSearch,
            totalcount,
            nowViewScope,
            leftTreeValueArray,
            title,
            menuid,
            visible,
            tabs,
            setRetainCondition,
            popSelectKey,
            setTotalCount,
            isOpenContinuationProcess,
            searchConditionParams,
            getOtherParams,
            nowScopeButtons,
            api_return_scopname,
            mobilecenter_button_manifestly,
			queryParams
        } = this.props.workflowCenterStore;

        const { secondAuthStore } = this.props;
        const { dialogVisible } = secondAuthStore;

        if (nowStore.leftTreeStore && nowStore.leftTreeStore.rowKey !== 'domid') {
            nowStore.leftTreeStore.setState({ rowKey: 'domid' });
        }
        let extraPrompt = (nowViewScope.name == "doing" || nowViewScope.name == "flowAll" && totalcount > 0) ? (<div className='wf-center-extraPrompt'>{getLabel(391151, "总共") + totalcount + getLabel(507611, "条数据")}</div>) : null;
        const Highlight = nowStore.islight;
        const color = Highlight ? '#55B1F9' : '';
        const searchPath = `${nowStore.path}/SearchAdvanced`;
        let heightSpace = (mobilecenter_button_manifestly == 1 && nowScopeButtons && nowScopeButtons.length > 0 && !showCheck) ? 47 : 0;//释放按钮高度
        const isShareSearch = (nowStore.searchAdvancedStore && nowStore.searchAdvancedStore.form && nowStore.searchAdvancedStore.form.formParams.viewcondition == '1')//共享流程列表，不显示左滑操作和批量提交等按钮
        const isResourceCard = queryParams.hasOwnProperty("resourceid") && parseInt(queryParams.resourceid, 0) != 0;//是否是人力资源卡片过来的请求，屏蔽底部按钮及左滑操作
        return (
            <div className='wf-center' style={{ overflow: "hidden"}}>

                <ListAdvanced
                    store={nowStore}
                    extraPrompt={!showCheck && (nowScope === 'doing' || (menuid > 0)) && totalcount > 0 ? extraPrompt : null}
                    rowKey="primarykeyspan"
                    treeKey="domid"
                    searchKey="requestname"
                    getSearchAdvancedDataMounted={false}
                    hasAdvanceSerach
                    dataFetchOptions={{
                        url: nowViewScope.dataURl + nowScope,
                    }}
                    conditionFetchOptions={{
                        url: nowViewScope.name === "all" || nowViewScope.name === "attentionAll" ? nowViewScope.conditionUrl : nowViewScope.treeUrl,
                        method: 'POST',
                        params: nowViewScope.name === "all" ? { belongPathTree: true } : {},
                    }}
                    leftTreeFetchOptions={{
                        url: nowViewScope.treeUrl,
                        method: 'POST',
                    }}
                    leftTreeBrowserProps={{
                        searchBarProps: {
                            placeholder: getLabel(391153, '请输入类型/路径名称'),
                        },
                        valueArray: toJS(leftTreeValueArray)
                    }}
                    searchBarProps={{
                        showSelectButton: true,
                        selectText: getLabel(63, '类型'),
                        onSelectButtonClick: () => console.log('跳转到树'),
                        placeholder: getLabel(391119, '请输入流程标题'),
                        extraButton: (menuid === -1 || (tabs && tabs.length > 1)) ? null : [
                            {
                                key: 'advanced', show: <Link to={searchPath}>
                                    <Icon
                                        type={`filter-o${Highlight ? '-hot' : ''}`}
                                        style={{ color }}
                                    />
                                </Link>
                            },
                        ]
                    }}
                    onHideCheck={() => {
                        changeCheck(false);
                        setState({ remark: "" });
                        nowStore.listViewStore.setState({ selectedRowKeys: [] });
                    }}
                    showCheck={showCheck}
                    onSubmit={(a, b, c, d) => {
                        // console.log(a, b, c, d);
                    }}
                    getDataCutom={true}
                    onRefresh={() => {
                        const { listViewStore } = nowStore;
                        const { dataKey } = listViewStore;
                        setTotalCount({ dataKey });
                    }}
                    onRowClick={

                        request => {
                            if ((showCheck && request.randomFieldCk === "false") || !showCheck) {//禁选
                                saveStore();
                                setRetainCondition();
                                if (request.appurlspan) {
                                    let timestamp = new Date().getTime();
                                    let url = request.appurlspan;
                                    if (url.includes("?")) {
                                        url = `${url}&timestamp=${timestamp}`
                                    } else {
                                        url = `${url}?timestamp=${timestamp}`
                                    }
                                    forwardViewPage(url, this.forwadCallback4Os({ requestid:request.requestid }));
                                } else {
                                    let urlParams = {
                                        requestid: request.requestid,
                                        f_weaver_belongto_userid: request.userid,
                                        f_weaver_belongto_usertype: request.usertype,
                                        timestamp: Date.parse(new Date()),
                                    }
                                    if(request.openByDefaultBrowserspan == 1){
                                        urlParams.openByDefaultBrowser = request.openByDefaultBrowserspan;
                                    }
                                    if (request.issup && request.issup == 1) {
                                        urlParams.urger = 1;
                                    }
                                    if((nowScope === 'doing' || getOtherParams()['mobileDimensionScope'] == 'doing') && isOpenContinuationProcess) {
                                        urlParams.isOpenContinuationProcess = 1;
                                        localStorage.continuationProcess_searchConditionParams = searchConditionParams;
                                    }
                                    forwardViewForm(urlParams, this.forwadCallback);
                                }

                            } else if (showCheck && request.randomFieldCk === "true") {
                                let selectedRowKeys = toJS(nowStore.listViewStore.selectedRowKeys)
                                if (selectedRowKeys.includes(request.primarykeyspan)) {
                                    selectedRowKeys.splice(selectedRowKeys.indexOf(request.primarykeyspan), 1)
                                    nowStore.listViewStore.setState({ selectedRowKeys })
                                } else {
                                    nowStore.listViewStore.setState({ selectedRowKeys: [...selectedRowKeys, request.primarykeyspan] })
                                }
                            }
                        }
                    }
                    withSwipeAction={!showCheck}
                    swipeActionProps={(isShareSearch || isResourceCard) ? [] : this.getSwipeActionProps()}
                    onLeftTreeChange={this.onLeftTreeChange}
                    onSearch={this.onSearch}
                    buttonGroupData={this.getButtonGroupData()}
                    heightSpace={heightSpace}

                />
                {needRemark && this.getRemark()}
                {dialogVisible.has(authTypes.SECOND_AUTH_DIALOG) && <SecondAuthDialog />}
                {
                    this.getRouteGroup()
                }

            </div>

        );
    }

    onSearch = () =>{
        const { workflowCenterStore } = this.props;
        workflowCenterStore.onSearch();
    }

    getRouteGroup = () => {
        const { workflowCenterStore } = this.props
        const { nowStore } = workflowCenterStore;
        let routeMap = {
            'follow': <FollowList store={workflowCenterStore} type={'workflowpage'} />,
            'tagManage': <TagManage store={workflowCenterStore} type={'workflowpage'} />,
            'tagEdit': <TagEdit store={workflowCenterStore} type={'workflowpage'} />,
        }
        let arr = [];
        for (let i in routeMap) {
            if (i == 'follow') {
                arr.push(
                    <Route
                        key={i}
                        path={nowStore.route + "/" + i}
                        render={() => (
                            <RouteLayout>
                                <div
                                    key="wmPoutePageDemo"
                                    className="wm-route-layout wm-demo-route-layout-page"
                                >
                                    {routeMap[i]}
                                </div>
                            </RouteLayout>
                        )}
                    />
                )
            } else if (i == 'tagManage') {
                arr.push(
                    <Route
                        key={i}
                        path={nowStore.route + "/follow/" + i}
                        render={() => (
                            <RouteLayout>
                                <div
                                    key="wmPoutePageDemo"
                                    className="wm-route-layout wm-demo-route-layout-page"
                                >
                                    {routeMap[i]}
                                </div>
                            </RouteLayout>
                        )}
                    />
                )
            } else if (i == 'tagEdit') {
                arr.push(
                    <Route
                        key={i}
                        path={nowStore.route + "/follow/tagManage/" + i}
                        render={() => (
                            <RouteLayout>
                                <div
                                    key="wmPoutePageDemo"
                                    className="wm-route-layout wm-demo-route-layout-page"
                                >
                                    {routeMap[i]}
                                </div>
                            </RouteLayout>
                        )}
                    />
                )
            }
        }

        //契约锁二次认证，因为只有待办才有批量提交，因此这里的根路由，默认是取的待办
        arr.push(
            <Route key="qysauth" path="/center/doing/qysauth" render={() => {
                return <RouteLayout>
                    <div key="qysauth" className="wm-route-layout">
                        <coms.QYSAuth ctype={1} />
                    </div>
                </RouteLayout>
            }}></Route>
        );

        return arr
    }

    getButtonGroupData() {
        const { nowStore, multisubmitnotinputsign, setState, nowScope, layout } = this.props.workflowCenterStore;
        let { menuid } = this.props.workflowCenterStore;
        menuid = parseInt(menuid, 10);
        let result = [];
        const currentBtn = this.props.workflowCenterStore.currentBtn;
        const btnName = btnNames[currentBtn];

        //if (menuid == -1 || menuid > 0) {//menuid == 1 || menuid == 2 || menuid == 3 
            result = [
                {
                    className: toJS(nowStore.listViewStore.selectedRowKeys).length === 0 || !nowStore.listViewStore.haveCheck ? "button-disable" : "",
                    key: 'submit',
                    text: btnName,
                    onClick: () => {
                        if (currentBtn == 'batchSubmit') {
                            if (toJS(nowStore.listViewStore.selectedRowKeys).length > 0 && nowStore.listViewStore.haveCheck)
                                if (multisubmitnotinputsign === 1) {
                                    setState({ needRemark: true });
                                } else {
                                    let requestid = toJS(nowStore.listViewStore.selectedRowKeys);
                                    /*requestBatchSubmit(
                                        requestid
                                    );*/
                                    let userids_arr = [];
                                    requestid.length > 0 && requestid.map(it => {
                                        userids_arr.push(it.split("+")[1]);
                                    })
                                    let belongtoUserids = userids_arr.join(",");
                                    //判断是否需要二次认证后再提交流程
                                    const params = { requestIds: requestid, remark: "", belongtoUserids };
                                    this.doSecondAuth(params);

                                    //setState({ showCheck: false });
                                }
                        } else if (currentBtn == 'batchSupervise') {//批量督办
                            if (toJS(nowStore.listViewStore.selectedRowKeys).length > 0 && nowStore.listViewStore.haveCheck) {
                                setState({ needRemark: true });
                            }
                        } else if (currentBtn == 'batchAttention') {
                            if (toJS(nowStore.listViewStore.selectedRowKeys).length > 0) {
                                let reqids = []
                                nowStore.listViewStore.selectedRowKeys.map(val => {
                                    reqids.push(val.split('+')[0])
                                })
                                this.props.history.push({
                                    pathname: nowStore.route + '/follow',
                                    state: {
                                        requestids: reqids.join(','),
                                        addressBack: this.props.location.pathname,
                                        mode: 'Cbatch', flag: 'workflow',
                                        route: nowStore.route,
                                    }
                                })
                            }
                        }
                    },
                    type: 'primary',
                }
            ];
        //}

        return result;
    }
    forwadCallback = (arg = {}) => {
        const { onSearch, showCheck } = this.props.workflowCenterStore;
        if (typeof arg === "string") {
            arg = JSON.parse(arg);
        }
        const { isReturn = false } = arg;
        if (isReturn || (!isReturn && showCheck)) {//走的返回
            onSearch({ notClearSelectedRowKeys: true });//不清空selectedRowKeys
        } else {//走的提交
            onSearch();
        }
    }
    // 异构系统 调用doReadIt来处理已读
    forwadCallback4Os = (arg = {}) => {
        const { onSearch, showCheck, doReadIt } = this.props.workflowCenterStore;
        doReadIt({"opertype":"single",requestid:arg.requestid});
        if (typeof arg === "string") {
            arg = JSON.parse(arg);
        }
        const { isReturn = false } = arg;
        if (isReturn || (!isReturn && showCheck)) {//走的返回
            onSearch({ notClearSelectedRowKeys: true });//不清空selectedRowKeys
        } else {//走的提交
            onSearch();
        }
    }

    getRemark() {
        const {
            setState,
            phrasesDatas,
            remark,
            nowStore,
            requestBatchSubmit,
        } = this.props.workflowCenterStore;
        const buttonGroup = [
            {
                key: 'reset',
                text: getLabel(201, '取消'),
                onClick: () => {
                    setState({ needRemark: false });
                },
            },
            {
                key: 'submit',
                text: getLabel(615, '提交'),
                onClick: () => {
                    //remark
                    /* requestBatchSubmit(
                         toJS(nowStore.listViewStore.selectedRowKeys),
                         remark
                     );*/
                    let userids_arr = []
                    let requestid = toJS(nowStore.listViewStore.selectedRowKeys)
                    requestid.length > 0 && requestid.map(it => {
                        userids_arr.push(it.split("+")[1]);
                    })
                    let belongtoUserids = userids_arr.join(",");
                    //是否需要二次认证后再提交流程
                    const params = { requestIds: requestid, remark, belongtoUserids };
                    this.doSecondAuth(params);

                    setState({ needRemark: false, showCheck: false });

                },
                type: 'primary',
            },
        ];
        return (
            <div className="wf-signView-panel">
                <div
                    className="wf-signView-panel-mask"
                />
                <div className="wf-signView-panel-content">
                    <div className="sign-panel-title">
                        {this.getPhraseCom(phrasesDatas, setState, remark)}
                    </div>
                    <div style={{ marginBottom: 60 }} className="sign-panel-main">
                        {this.getRemarkEditor(setState, remark)}
                    </div>
                </div>
                <div className="sign-panel-bottom">
                    <ButtonGroup data={buttonGroup} />
                </div>

            </div>
        );
    }

    getRemarkEditor(setState, remark) {
        const modules = { toolbar: false };
        return (
            <TextareaItem
                value={remark}
                modules={modules}
                placeholder={getLabel(391154, '请输入签字意见')}
                onChange={v => {
                    setState({ remark: v })
                }}
                //height={160}
                rows={4}
            />
        );
    }

    //常用批示语组件
    getPhraseCom(phraseInfo = [], setState, remark) {
        let menuData = [];
        phraseInfo.map(item => {
            const { desc = '', short = '' } = item;

            menuData.push({ value: this.convertSpecialChar(desc), label: short });
        });
        return (
            <Picker data={menuData} cols={1} onOk={v => {
                remark = `${remark}${v}`;
                setState({ remark });
            }}>
                <div className={'sign-phrase-title'}>
                    <span className={'span-title'}>{getLabel(391155, "常用批示语")}</span>
                    <Icon type="down" />
                </div>
            </Picker>
        );
    }


    convertSpecialChar = (str) => {
        str = str.toString();
        str = str.replace(/<br>/ig, "\n");
        str = str.replace(/&nbsp;/ig, " ");
        str = str.replace(/&lt;/ig, "<");
        str = str.replace(/&gt;/ig, ">");
        str = str.replace(/&quot;/ig, "\"");
        str = str.replace(/&amp;/ig, "&");
        let reTag = /<(?:.|\s)*?>/g;
        return str.replace(reTag, "");
    }

    /**
     * 跳转到新建流程
     */
    doLinktoAddRequest() {
        this.props.history.push({ pathname: '/add' });
    }

    doSecondAuth(params) {
        const { secondAuthStore } = this.props;
        const { requestIds, remark, belongtoUserids } = params;

        let idarr = requestIds.map(v => {
            const arr = v.split("+");
            const requestid = arr[0];
            return requestid;
        });

        let reqids = idarr.join(",");

        const { isAuthSuccess, isProtectSuccess } = secondAuthStore;
        //已验证通过或者已数据保护通过
        if (isAuthSuccess == 1 || isProtectSuccess == 1) {
            const { isEnableAuth, secondAuthType, isEnableProtect, protectType, qysSignWay = 2, authKey } = secondAuthStore;
            if (isProtectSuccess != 1 && isEnableProtect == 1) {      //仍然需要数据保护
                if (protectType == authTypes.QYS && qysSignWay == 2) {     //契约锁数据保护
                    const isProtectDialog = 1;    //1表示打开的是契约锁数据保护的窗口
                    secondAuthStore.setCAAuthData({ isProtectDialog });

                    secondAuthStore.setCallbackFunc(this.doSecondAuth.bind(this));
                    secondAuthStore.setCallbackParam(params);

                    //弹出数据保护的窗口
                    openQYSAuth();
                    return;
                }
            }


            //能运行到这里，说明已经做完了数据保护
            if (isEnableProtect == 1) {
                if (protectType == authTypes.CA_AUTH || (protectType == authTypes.QYS && qysSignWay == 1)) {
                    params = { ...params, authKey, isProtectSuccess };
                }
            }

            //契约锁数据保护或者认证
            if (protectType == authTypes.QYS || secondAuthType == authTypes.QYS) {
                const { authResult } = secondAuthStore;
                const { qysSealId, qysSealImg, qysCertDetails } = authResult;
                params = { ...params, qysSealId, qysSealImg, qysCertDetails };
            }

            params.protectType = protectType;
            params.secondAuthType = secondAuthType;
            params.isAuthSuccess = isAuthSuccess;
            params.qysSignWay = qysSignWay;

            this.doSecondAuthBack(params);
        } else {
            getSecondAuthConfig4List({ requestIds: reqids }).then(checkResult => {
                const { isEnableAuth = 0, secondAuthType = 0, isEnableProtect = 0, protectType = 0, qysSignWay = 2, message = "", success, signUrl = "" } = checkResult;

                if (success == "0") {
                    if (!!message) {
                        Bubble.error(message, 1);
                        return;
                    }
                }

                secondAuthStore.setDialogData({ isEnableAuth, secondAuthType, isEnableProtect, protectType, qysSignWay, signUrl });
                //如果开启了数据保护或者数据验证，但是没有不是在EM app上执行操作，就提示
                if (!secondAuthStore.canDoSecondAuth()) {
                    return;
                }
                if (isEnableAuth == 1) {      //需要二次认证
                    let isProtectDialog = 0;

                    //同时是契约锁认证和数据保护
                    if (secondAuthType == authTypes.QYS && qysSignWay == 2 && isEnableProtect == 1 && protectType == authTypes.QYS) {
                        isProtectDialog = 10;    //10表示打开的是契约锁二次认证 + 契约锁数据保护的窗口
                    }

                    //批量提交时，CA只有二次认证，没有数据保护
                    if (secondAuthType == authTypes.CA_AUTH || (secondAuthType == authTypes.QYS && qysSignWay == 1)) {
                        //验证时，sourcestr的值为空，但是ca认证时这个值又是必须的，因此初始化一个随机值
                        const { authKey, sourcestr = Math.random() } = checkResult;
                        secondAuthStore.setCAAuthData({ authKey, sourcestr });
                    }

                    secondAuthStore.setCAAuthData({ isProtectDialog });		//设置认证的数据
                    //弹出验证或者数据保护的窗口
                    secondAuthStore.setCallbackFunc(this.doSecondAuth.bind(this));
                    secondAuthStore.setCallbackParam(params);
                    if (secondAuthType == authTypes.QYS && qysSignWay == 2) {      //契约锁二次认证或者数据保护
                        openQYSAuth();
                    } else if (secondAuthType == authTypes.QYS && qysSignWay == 1) {
                        QYSUKeyUtil.showSignWin(secondAuthStore);
                    } else {       //其他二次认证或者数据保护
                        secondAuthStore.controlDialogVisible(authTypes.SECOND_AUTH_DIALOG, true);
                    }
                } else {     //没有开启二次认证
                    if (isEnableProtect == 1) {
                        secondAuthStore.setCallbackFunc(this.doSecondAuth.bind(this));
                        secondAuthStore.setCallbackParam(params);

                        if (protectType == authTypes.QYS && qysSignWay == 2) {       //契约锁数据保护,也需要打开窗口，让用户选择签章
                            const isProtectDialog = 1;    //1表示打开的是契约锁数据保护的窗口
                            secondAuthStore.setCAAuthData({ isProtectDialog });
                            openQYSAuth();
                        }
                    } else {     //没有开启数据保护
                        this.doSecondAuthBack(params);
                    }
                }

                /*if (isEnableAuth == 1) {      //需要二次验证
                    secondAuthStore.setCallbackFunc(this.doSecondAuthBack.bind(this));
                    secondAuthStore.setCallbackParam(params);
                    secondAuthStore.setDialogData({secondAuthType});
                    secondAuthStore.setCAAuthData({authKey});
                    secondAuthStore.controlDialogVisible(authTypes.SECOND_AUTH_DIALOG, true);
                } else {     //不需要，提交签字意见
                    this.doSecondAuthBack(params);
                }*/
            });
        }
    }

    doSecondAuthBack(params) {
        const { requestBatchSubmit, setState, tabName } = this.props.workflowCenterStore;
        const { secondAuthStore } = this.props;
        const requestIds = params.requestIds;
        const remark = params.remark;
        const belongtoUserids = params.belongtoUserids;
        requestBatchSubmit(requestIds, remark, belongtoUserids, params, () => {
            secondAuthStore.resetStore();
        });
        setState({ needRemark: false, showCheck: false });
    }
}


export default WorkflowCenter;

export const loadList = () => {
    const { onSearch } = allStore.workflowCenterStore;
    onSearch({ notClearSelectedRowKeys: true });
}
window.loadList = loadList;